package cn.hiapi.shopkeeper.task;

import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.token.enums.TokenType;
import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.finance.IAssetsService;
import cn.hiapi.interfaces.finance.IPaymentService;
import cn.hiapi.interfaces.finance.model.AmountChange;
import cn.hiapi.shopkeeper.consts.AppConst;
import cn.hiapi.shopkeeper.entity.order.ActivityGroupOrder;
import cn.hiapi.shopkeeper.entity.order.ActivityOrder;
import cn.hiapi.shopkeeper.enums.ActivityType;
import cn.hiapi.shopkeeper.enums.OrderStatus;
import cn.hiapi.shopkeeper.service.order.ActivityGroupOrderService;
import cn.hiapi.shopkeeper.service.order.ActivityOrderService;
import cn.hiapi.shopkeeper.task.abs.AbsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author AdinZ
 * @date 2023/1/2 23:39
 */
@Component
@Slf4j
public class OrderGroupTaskService extends AbsTaskService {

    public OrderGroupTaskService(DispatchContext dispatchContext) {
        super(dispatchContext);
    }


    /**
     * 监听活动结束任务
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void orderClose() {
        List<ActivityGroupOrder> list = this.dispatchContext.getServiceOne(ActivityGroupOrderService.class)
                .findList(new QueryWrapper().eq("status", 1).le("expire", System.currentTimeMillis()));

        for (ActivityGroupOrder groupOrder : list) {
            groupOrder.setStatus(3);//成团失败
            groupOrder.setUpdated(System.currentTimeMillis());
            this.dispatchContext.getServiceOne(ActivityGroupOrderService.class).save(groupOrder);
            log.info("[团购活动监听] 团购超时未成团关闭团购:{}", groupOrder);
            //TODO  成团失败,进行退款

            List<ActivityOrder> orders = this.dispatchContext.getServiceOne(ActivityOrderService.class).findList(new QueryWrapper()
                    .eq("activityType", ActivityType.GROUP).eq("fid", groupOrder.getId()).eq("statusType", 1));

            orders.forEach(order -> {
                order.setStatus(OrderStatus.GROUP_FAIL);
                order.setUpdated(System.currentTimeMillis());
            });
            this.dispatchContext.getServiceOne(ActivityOrderService.class).save(orders);
        }
    }


    @Scheduled(cron = "0 0/1 * * * ?")
    public void groupFailRefund() {
        List<ActivityOrder> list = this.dispatchContext.getServiceOne(ActivityOrderService.class).findList(new QueryWrapper()
                .eq("activityType", ActivityType.GROUP).eq("status", OrderStatus.GROUP_FAIL).eq("statusType", 1));
        for (ActivityOrder order : list) {

            if (StringUtils.equals(order.getPayType(), "money")) {
                this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                        .title("团购失败 - " + order.getTitle()).remark("团购失败 - " + order.getTitle())
                        .sourceId(order.getId()).remark(AppConst.PAY_CALL_TYPE_ORDER)
                        .amount(order.getPayment()).type(AppConst.FINANCE_AMOUNT_MONEY)
                        .fid(order.getBuyerId()).fidType(TokenType.ROLE_USER).mid(0)
                        .build());

            } else {
                this.dispatchContext.getServiceOne(IPaymentService.class).createRefund(order.getId(), AppConst.PAY_CALL_TYPE_ORDER);
            }

            if (order.getSugar().compareTo(BigDecimal.ZERO) > 0) {
                this.dispatchContext.getServiceOne(IAssetsService.class).changeAmount(AmountChange.builder()
                        .title("团购失败 - " + order.getTitle()).remark("团购失败 - " + order.getTitle())
                        .sourceId(order.getId()).remark(AppConst.PAY_CALL_TYPE_ORDER)
                        .amount(order.getSugar()).type(AppConst.FINANCE_AMOUNT_SUGAR)
                        .fid(order.getBuyerId()).fidType(TokenType.ROLE_USER).mid(0)
                        .build());
            }

            order.setStatusType(0);
            order.setUpdated(System.currentTimeMillis());
            this.dispatchContext.getServiceOne(ActivityOrderService.class).save(order);
        }
    }


}
